<?php

namespace app\common\model;

class AuthGroupModel extends BaseModel
{

  protected $table = 'auth_group';

  /**
   * 添加权限组
   * @param $data
   * @return mixed
   */
  public function add($data)
  {
    return self::create($data);
  }

  /**
   * 修改权限组
   * @param $data
   * @return mixed
   * @throws \Exception
   */
  public function edit($data)
  {
    return self::update($data);
  }

  /**
   * 删除权限组
   * @param $id
   * @return mixed
   * @throws \Exception
   */
  public function del($id)
  {
    if (AdminModel::where('group_id', $id)->find()) abort(500, '该组已被使用');
    return $this->where('id', $id)->delete();
  }

  /**
   * 获取指定用户组权限
   * @param $groupId
   * @return array
   * @throws \Exception
   */
  public function getRule($groupId = 0)
  {
    $authRuleModel = new AuthRuleModel();
    $ruleList      = $authRuleModel->getList(); //所有权限
    //获取该角色组拥有权限
    $groupRules   = $this->where('id', $groupId)->value('rules');
    $groupRuleIds = empty($groupRules) ? [] : explode(',', $groupRules); //用户组对应权限ID数组
    $rule         = [];
    foreach ($ruleList as $v) {
      $checked = in_array($v['id'], $groupRuleIds) ? true : false;
      $rule[]  = ['id' => $v['id'], 'pid' => $v['pid'], 'title' => $v['title'], 'checked' => $checked, 'open' => true];
    }
    return $rule;
  }

}
